<template>
    <div>
        <div class="common-layout" style=" margin: 0 30%;">
            <div>
                <el-container>
                    <el-aside width="200px">
                        <!-- 使用 el-tree 组件展示树形数据 -->
                        <el-tree :data="RoleModel" :highlight-current="true" ref="treeRef" :props="treePropsRole"
                            node-key="roleId" @node-click="handleNodeClickRole">
                        </el-tree>
                        <!-- 显示点击节点的 roleId -->
                        <div v-if="AddModel.roleId">当前选中的 roleId 是: 【{{ AddModel.roleId }}】</div>
                    </el-aside>
                    <el-aside width="200px">
                        <div>
                            <!-- 使用 el-tree 组件 -->
                            <el-tree :data="treeData" :default-checked-keys="AddModel.menuId" show-checkbox
                                node-key="menuId" :props="defaultPropsMenu" @check-change="handleCheckChange"
                                ref="treeRef" :default-expand-all="true"></el-tree>
                            <!-- 显示选中的 menuId -->
                            <p>当前选中的 menuId: {{ AddModel.menuId }}</p>
                        </div>
                    </el-aside>
                </el-container>
            </div>
            <div>
                <el-button type="success" @click="AddRoleMenu">保存</el-button>
            </div>
        </div>
    </div>
</template>

<script setup lang="ts">
//#region import
import { ElMessage } from 'element-plus';
import { nextTick, onMounted, reactive, ref } from 'vue'
import { useRouter } from 'vue-router';
import { useCounterStore } from '@/stores/counter';
import axios from 'axios';
import { ElTree } from 'element-plus';
const apiUrl = import.meta.env.VITE_APP_API_URL;
//pini保存
const store = useCounterStore();
//跳转
const router = useRouter();

//#endregion

//#region  获取角色数据(id,名称)

//获取角色的数据
const RoleModel = ref([])
//获取角色数据(id, 名称)
const GetRole = () => {
    axios.get(apiUrl+'/T5/Message/GetRole', {}).then(res => {
        RoleModel.value = res.data.data
        console.log(RoleModel.value, "角色名称")
    })
}

// 定义树的属性配置
const treePropsRole: any = ref({
    label: 'roleName', // 指定节点的标签显示字段为 roleName
    children: [] // 指定子节点字段为 children
});






// 处理节点点击事件(通过roleId 查询 菜单数据实现反填)
const handleNodeClickRole = (data: any) => {
    //清空节点
    AddModel.menuId = [];
    AddModel.roleId = data.roleId;
    // https://localhost:7174/api/Message/GetMenuAll         这个链接为获取全部菜单信息
    // `https://localhost:7174/api/Message/GetMenuListByRoleId?RoleId=${data.roleId}` 这个为根据登录人获取相对应的菜单
    axios.get(apiUrl+'/T5/Message/GetMenuAll').then(res => {
        AddModel.menuId = res.data.data.map((item: any) => item.menuId)
        console.log(res.data.data, '反填菜单名称res')
        console.log(AddModel.menuId, '反填菜单名称')
        nextTick()
        // 强制更新 el-tree 的选中状态
        treeRef.value.setCheckedKeys(AddModel.menuId);
    })
};

//#endregion


//#region  获取菜单数据(id,名称)

//获取菜单的数据
const MenuModel = ref([])
// 存储树形结构的数据
const treeData = ref([]);
//获取菜单数据(id, 名称)
const GetMenu = () => {
    axios.get(apiUrl+'/T5/Message/GetMenuAll').then(res => {
        MenuModel.value = res.data.data
        console.log(MenuModel.value, "赋值MenuModel.value")
        console.log(res.data.data, "获取res.data.data")
        treeData.value = convertToTree(MenuModel.value)
        console.log(treeData.value, "获取树形菜单")
    })
}

// 将普通数组转换为树形结构
const convertToTree = (data: any) => {
    const tree: any = [];
    const map: any = {};

    // 先将每个节点存储到 map 中
    data.forEach((item: any) => {
        map[item.menuId] = { ...item, children: [] };
    });

    // 再根据 parentId 构建树形结构
    data.forEach((item: any) => {
        if (item.pId === 0) {
            tree.push(map[item.menuId]);
        } else {
            const parent = map[item.pId];
            if (parent) {
                parent.children.push(map[item.menuId]);
            }
        }
    });
    return tree;
};

// 获取 el-tree 组件的引用
const treeRef = ref<InstanceType<typeof ElTree>>();

// 定义 tree 组件的属性配置
const defaultPropsMenu = {
    children: 'children',
    label: 'menuName'
};

// 存储选中节点的 id 数组
const checkedIds: any = ref([]);



//获取菜单多选值
const handleCheckChange = () => {
    AddModel.menuId = treeRef.value?.getCheckedKeys() || [];
    console.log(AddModel.menuId, '获取单个选中值')
};


const AddModel: any = reactive({
    "roleId": "",
    "menuId": []
})


//#endregion

//#region 添加
const AddRoleMenu = () => {
    if (AddModel.roleId == "") {
        ElMessage.error("请选择角色")
        return;
    }
    console.log(AddModel.menuId)
    console.log(AddModel.roleId)
    axios.post(apiUrl+'/T6/Message/AddRoleMenu', AddModel).then(res => {
        if (res.data.code == 212) {
            ElMessage.success(res.data.msg)
        }
    })
}

//#endregion



onMounted(() => {
    GetRole()
    GetMenu()
})
</script>
